<template>
  <div class="container">
    <!-- 上传图片表单 -->
    <n-form
      ref="formRef"
      :model="model"
      :rules="rules"
      :size="size"
    >
      <n-form-item path="files">
        <template #label>
          请选择需要上传的图片
          <n-tooltip trigger="hover">
            <template #trigger>
              <n-icon :size="20" style="vertical-align: bottom;">
                <HelpCircleOutline />
              </n-icon>
            </template>
            一次最多上传20张图片，单张图片大小不能超过20M。
          </n-tooltip>
          ：
        </template>
        <div style="display: flex; align-items: flex-start">
          <n-upload
            ref="uploadRef"
            :multiple="true"
            :default-upload="false"
            @update:file-list="handleUpdateFileList"
            @before-upload="handleBeforeUpload"
          >
            <n-button type="primary">上传图片</n-button>
          </n-upload>
          <n-button type="primary" @click="handleClearPicture">清空</n-button>
        </div>
      </n-form-item>
      <n-form-item
        label="输出图片文件夹路径："
        path="pathTwo"
      >
        <n-input
          v-model:value="model.pathTwo"
          placeholder="请输入输出图片文件夹路径"
        >
          <template #prefix>
            <span>{{ "/" + userInfo.pic_url + "/" }}</span>
          </template>
        </n-input>
      </n-form-item>
      <n-form-item label="图片拍摄时间：" path="captureTime">
        <n-date-picker
          v-model:formatted-value="model.captureTime"
          placeholder="请输入图片拍摄时间"
          type="date"
          value-format="yyyy-MM-dd"
        />
      </n-form-item>
      <div style="display: flex; justify-content: center">
        <n-button round type="primary" @click="handleUpload">
          上传
        </n-button>
      </div>
    </n-form>

    <!-- 上传日志显示 -->
    <div class="log">
      <div v-for="(log, index) in uploadLogInfos" :key="index" class="log-item">
        <span>文件：{{ log.filename || "" }}&nbsp;&nbsp;&nbsp;、</span>
        <span>{{ log.msg || "" }}&nbsp;&nbsp;&nbsp;。</span>
      </div>
    </div>

    <!-- 上传进度条 -->
    <div v-if="showProgress" class="progress">
      <n-progress
        type="line"
        rail-color="#fefefe"
        :percentage="percentage"
        :indicator-placement="'inside'"
        processing
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  NForm,
  NInput,
  NDatePicker,
  NButton,
  NUpload,
  UploadFileInfo,
  NProgress,
  FormItemRule,
  NIcon,
  NTooltip,
} from "naive-ui";
import { Ref, ref } from "vue";
import dayjs from "dayjs";
import { pictureUpload } from "../../api/pictrue";
import { computed } from "vue";
import appStore from "@/packages/pinia/app"
const { userInfo } = appStore();

const formRef = ref<any>(null);
const size = ref("medium");
const uploadRef = ref<any>(null);

const model = ref({
  files: null, // 本地文件
  pathTwo: "", // 输出图片文件夹路径
  captureTime: dayjs().format("YYYY-MM-DD"), // 拍摄时间
});

const rules = {
  files: {
    required: true,
    trigger: ["blur", "input"],
    validator: (rule: FormItemRule, value: string) => {
      return new Promise<void>((resolve, reject) => {
        if (!fileLists.value.length || fileLists.value.length > 20) {
          reject(new Error('请选择图片且数量不能超过20张'));
        } else {
          resolve()
        }
      })
    }
  },
  captureTime: {
    required: true,
    trigger: ["blur", "input"],
    message: "请输入图片拍摄时间",
  },
};

const fileLists = ref<UploadFileInfo[]>([]); // 最终的文件列表
const fileListLens = computed(() => fileLists.value.length); // 文件列表长度
const uploadLogInfos: Ref<ObjectType[]> = ref([]); // 上传日志信息
const showProgress = ref(false); // 是否显示上传进度
const percentage = ref<number>(0); // 上传进度

// 保存选中的图片列表
const handleUpdateFileList = (fileList: UploadFileInfo[]) => {
  fileLists.value = fileList;
};

// 图片上传前的校验
const handleBeforeUpload = ({
  file,
  fileList,
}: {
  file: UploadFileInfo;
  fileList: UploadFileInfo[];
}) => {
  if (!file.type || file.type.indexOf("image") === -1) {
    window.$message.error("请上传图片文件");
    return false;
  } else if (file.file && file.file.size > 20 * 1024 * 1024) {
    window.$message.error("请上传小于20M的图片");
    return false;
  } else {
    return true;
  }
};

// 图片批量上传
const handleUpload = () => {
  formRef.value.validate(async (valid: any) => {
    if (!valid) {
      if (!userInfo.pic_url) {
        return window.$message.error("用户前缀路径不能为空");
      }
      showProgress.value = true;
      uploadLogInfos.value = [];
      for (const index in fileLists.value) {
        let info = {};
        const file = fileLists.value[index];
        console.log("upload file", file);
        const formData = new FormData();
        formData.append("file", file.file as any);
        formData.append("pathOne", userInfo.pic_url);
        model.value.pathTwo && formData.append("pathTwo", model.value.pathTwo);
        formData.append("captureTime", model.value.captureTime);
        await pictureUpload(formData)
          .then((res: any) => {
            console.log("upload result", res);
            if (res.status === "success") {
              window.$message.success(`图片${file.name}${res.msg}`);
            } else {
              window.$message.error(`图片${file.name}${res.msg}`);
            }
            info = res.data;
          })
          .catch((err: any) => {
            console.log("upload result1", err);
            const data = err.data?.data || {};
            window.$message.error(`图片${data.filename}${data.msg}`);
            info = data;
          });
        uploadLogInfos.value.push(info);
        percentage.value = Number(((Number(index) + 1) / fileListLens.value).toFixed(2)) * 100;
      }
      showProgress.value = false;
      percentage.value = 0;
      handleClearPicture();
    } else {
      window.$message.error("请检查输入项");
    }
  });
};

const handleClearPicture = () => {
  fileLists.value = [];
  uploadRef.value.clear();
};
</script>

<style scoped lang="less">
.container {
  height: 100%;
  border-radius: 5px;
  padding: 8px;
  background-color: #fff;
  overflow: auto;
  .n-form {
    flex: auto;
    margin-bottom: 20px;
  }
  .log {
    height: 150px;
    overflow: auto;
    padding: 8px;
    border-top: 1px solid #efefef;
  }
  :deep(.n-upload-file-list) {
    max-height: 150px;
    overflow: auto;
    &::-webkit-scrollbar {
      width: 8px;
      border-radius: 8px;
      background-color: #f5f5f5;
    }
    &::-webkit-scrollbar-thumb {
      border-radius: 8px;
      background: #b8b8b8;
    }
  }
  .n-upload {
    width: 400px;
  }

  &::-webkit-scrollbar {
    width: 8px;
    border-radius: 10px;
    background: #efefef;
  }
  &::-webkit-scrollbar-thumb {
    width: 6px;
    border-radius: 10px;
    background: #9e9797;
  }
}
.progress {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgb(31 30 30 / 10%);
  z-index: 9999;
  display: flex;
  justify-content: center;
  align-items: center;
  .n-progress {
    width: 200px;
  }
}
</style>
